﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Browsers;
using Wydatki.WRK.Praca.DataSets;
using ProgNetComponentsDx.Options;

namespace Wydatki.WRK.Praca
{
    public partial class FormWrkKpir : MyBaseSqlCeGridForm
    {
        private int Rok;
        private BindingList<SumRow> sumBindingList;
        private SumRowCollection sumRows = new SumRowCollection();

        public FormWrkKpir()
            : this(Settings.RokPodatkowy == null ? DateTime.Now.Year : Settings.RokPodatkowy.Value)
        {

        }

        public FormWrkKpir(int rok):base()
        {
            InitializeComponent();
            WydatkiGlobals.Events.DefPrevMonth(this.repositoryItemDateEdit1);

            this.Controls.Remove(gcMain);
            gcMain.Dock = DockStyle.Fill;
            this.splitContainerControl1.Panel1.Controls.Add(gcMain);
            foreach (DataRow r in BrowserCache.GetBrowserData(Init.InitFormBrowserNames.Glowna.GrupyKpir).Rows)
            {
                sumRows.Add(new SumRow { Suma = 0, Typ = r["STP_GRKPIR_KOD"].AsString() });
            }
            sumBindingList = new BindingList<SumRow>(sumRows);
            gridControl1.DataSource = sumBindingList;

            this.selectDataProvider1.GetSettings(this).Parameters["ROK"].Value = rok;
            Rok = rok;
            this.Text += " [Rok: " + rok + "]";
        }

        protected override void FinishEdit()
        {
            base.FinishEdit();
            DateTime dt;
            foreach (DataRow r in wrkKpirDataSet.WRK_KPIR.Rows)
            {
                if (r.CanRead() && r["WRK_KPIR_DATA"].IsNotNull())
                {
                    dt = r["WRK_KPIR_DATA"].AsDateTime(DateTime.MinValue);
                    if (dt.Year != r["WRK_KPIR_ROK"].AsInt())
                        r["WRK_KPIR_ROK"] = dt.Year;
                }
            }
        }
        protected override bool Save()
        {
            WrkKpirDataSet ds = wrkKpirDataSet.Copy() as WrkKpirDataSet;
            bool res  = base.Save();
            if (res)
            {
                if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Work.AddKpirToWydatki))
                {
                    Tools.WydatkiTools.ProcessNewWydatki(ds);
                }
                this.GetRecords();
            }
            return res;
        }
        protected override bool ValidateAll()
        {
            bool res = base.ValidateAll();
            if (res)
                res = ValidateRok();

            if (res)
            {
                DataRow[] rows = wrkKpirDataSet.WRK_KPIR.Select("WRK_KPIR_ROK <> " + Rok);
                if (rows.Length > 0)
                {
                    string msg = "Nie wszystkie wpisy są z roku " + Rok;
                    DialogResult dlg = this.ShowDxYNQuestionDialog(msg + "\nCzy chcesz zapisac dane?");
                    if (dlg == System.Windows.Forms.DialogResult.No)
                    {
                        res = false;
                        ValidationMessage = msg;

                        foreach (DataRow r in rows)
                            r.SetColumnError("WRK_KPIR_DATA", "Zły rok.");
                    }
                }
            }
            return res;
        }
        private bool ValidateRok()
        {
            bool res = true;
            DataRow[] rows = wrkKpirDataSet.WRK_KPIR.Select();
            List<int> invalid = new List<int>();
            int rok;
            Browser b = browserProvider1.GetBrowser(Init.InitFormBrowserNames.Glowna.LataPodatkowe);
            foreach (DataRow r in rows)
            {
                rok = r["WRK_KPIR_ROK"].AsInt();
                if (!b.IsValid(false, rok))
                {
                    invalid.AddIfNotExist(rok);
                    r.SetColumnError("WRK_KPIR_DATA", "Brak roku podatkowego.");
                }
            }
            if (invalid.Count > 0)
            {
                res = false;
                foreach (int i in invalid)
                    ValidationMessage = ValidationMessage.AppendLine("Brak roku podatkowego " + i);
            }

            return res;
        }
        private void repositoryItemButtonEdit1_Settings_AdditionalBrowserValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            e.Cancel = true;
            FinishEdit();
            DataRow r = gvMain.GetFocusedDataRow();
            if (r == null)
            {
                gvMain.AddNewRow();
                gvMain.UpdateCurrentRow();
                r = gvMain.GetFocusedDataRow();
            }
            if (r != null)
            {
                int i = e.NewValue.AsInt(-1);
                if (i > -1)
                {
                    SetupIpmortTools.AddKpirFromDef(wrkKpirDataSet, i, r);
                }
            }
        }

        private void bbiSaveAs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FinishEdit();
            DataRow r = gvMain.GetFocusedDataRow();
            if (r != null)
            {
                SetupIpmortTools.SaveKpirAsDef(r);
            }
        }

        private void gvMain_CustomSummaryCalculate(object sender, DevExpress.Data.CustomSummaryEventArgs e)
        {
            if (e.SummaryProcess == DevExpress.Data.CustomSummaryProcess.Finalize)
            {
                DataRow r = gvMain.GetDataRow(e.RowHandle);
                if (r != null)
                {
                    DataRow[] rows = r.GetChildRows(r.Table.ChildRelations[0]);
                    decimal dec = 0;
                    foreach (DataRow rr in rows)
                    {
                        dec += rr["WRK_KPIRK_KWOTA_NETTO"].AsDecimal();
                    }
                    e.TotalValue = dec;
                }

            }
        }

        private void gvMain_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            sumRows.ClearSum();
            try
            {
                int rh;
                if (gvMain.IsGroupRow(e.FocusedRowHandle))
                    rh = gvMain.GetDataRowHandleByGroupRowHandle(e.FocusedRowHandle);
                else
                    rh = e.FocusedRowHandle;
                
                DataRow r = gvMain.GetDataRow(rh);
                Dictionary<string, decimal> sumy = new Dictionary<string, decimal>();

                if (r != null)
                {
                    int miesiac = gvMain.GetRowCellValue(rh, colMiesiac).AsInt();
                    if (miesiac < 1)
                        return;
                    DateTime dtOd = new DateTime(Rok, miesiac, 1);
                    DateTime dtDo = dtOd.AddMonths(1);

                    DataRow[] kpirRows = wrkKpirDataSet.WRK_KPIR.Select("WRK_KPIR_DATA >= " + dtOd.ToString().EscapeSql() + " AND WRK_KPIR_DATA < " + dtDo.ToString().EscapeSql(), null, DataViewRowState.CurrentRows);
                    string kpirs = "";
                    foreach (DataRow kp in kpirRows)
                    {
                        kpirs = kpirs.AppendString(",");
                        kpirs += kp["WRK_KPIR_ID"].AsString();
                    }

                    if (kpirs.IsNotNull())
                    {
                        DataRow[] kwoty = wrkKpirDataSet.WRK_KPIR_KWOTY.Select("WRK_KPIRK_FAKTURA in (" + kpirs + ")", null, DataViewRowState.CurrentRows);
                        foreach (DataRow kw in kwoty)
                            sumRows[kw["WRK_KPIRK_TYP"].AsString()].Suma += kw["WRK_KPIRK_KWOTA_NETTO"].AsDecimal();
                    }
                }
                else
                {
                    sumRows.ClearSum();
                }
                gvSumy.RefreshData();
            }
            catch (Exception ex)
            {
                Tools.Globals.HandleException(ex);
            }
        }

        private void gvChild_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            gvMain_FocusedRowChanged(gvMain, new DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs(gvMain.FocusedRowHandle, gvMain.FocusedRowHandle));
        }

    }
}
